package com.dacool.fragment;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.dialog.MyProgressDialog;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.LoginRequest;
import com.dacool.model.DCUser;
import com.dacool.util.ViewUtils;

public class LoginFragment extends BaseFragment implements OnClickListener {

	private EditText accountInput;
	private EditText passwordInput;
	private Button loginButton;
	private Button registerButton;

	private MyProgressDialog mpdg;

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_login;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.setHasOptionsMenu(true);
		super.onViewCreated(view, savedInstanceState);
		loginButton = ViewUtils.findViewById(view, R.id.loginbutton);
		accountInput = ViewUtils.findViewById(view, R.id.accountinput);
		passwordInput = ViewUtils.findViewById(view, R.id.passwordinput);
		registerButton = ViewUtils.findViewById(view, R.id.registerbutton);
		loginButton.setOnClickListener(this);
		registerButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == loginButton) {
			if (validateInput())
				performLogin();
		} else if (v == registerButton) {
			performRegister();
		}

	}

	private void performLogin() {
		LoginRequest request = new LoginRequest();
		request.setName(accountInput.getText().toString().trim()).setPwd(
				passwordInput.getText().toString());

		this.showProgressDialog("登录中", false);
		request.setHandler(new ResponseHandler() {

			@Override
			public void handleResponse(BaseRequest request, int statusCode,
					String errorMsg, String response) {
				LoginFragment.this.dismissProgressDialog();
//				Log.d("test", "statusCode " + statusCode + ", response:"
//						+ response);
				if (statusCode == 200) {
					boolean success = false;
					String errmsg = null;
					try {
						JSONObject object = new JSONObject(response);
						success = object.optBoolean("success", false);
						errmsg = object.optString("msg", null);
						String memberID = object.optString("memberId", null);
//						Log.d("test", "login result:" + success + ",memberId:"
//								+ memberID);
						if (success && memberID != null) {
							DCUser.sharedUser().setName(
									accountInput.getText().toString().trim());
							DCUser.sharedUser().setPassword(
									passwordInput.getText().toString());
							DCUser.sharedUser().setUserId(memberID);
							DCUser.sharedUser().save();
							ViewUtils.runInMainThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									getContainerActivity().finish();
								}
							});
						} else {
							String msg = errmsg!=null?errmsg:"登录失败";
							ViewUtils.showToast(msg, Toast.LENGTH_LONG);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					ViewUtils.showToast("网络连接失败", Toast.LENGTH_LONG);
				}

			}
		});
		request.start();
	}

	private void performRegister() {
		RegisterFragment fragment = new RegisterFragment();
		getContainerActivity().addFragment(fragment);
	}

	private boolean validateInput() {
		Pattern p = Pattern.compile("^1\\d{10}$");
		Matcher matcher = p.matcher(accountInput.getText().toString());
		if (!matcher.matches()) {
			Toast.makeText(getActivity(), "请输入11位手机号", Toast.LENGTH_LONG)
					.show();
			return false;
		}
		if (passwordInput.getText().length() == 0) {
			Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "用户登录";
	}

	// @Override
	// public void onPrepareOptionsMenu(Menu menu) {
	// // TODO Auto-generated method stub
	// if (Config.DEV_MODE) {
	// menu.clear();
	// menu.add(0, 0, 0, "设置服务器地址");
	// }
	// super.onPrepareOptionsMenu(menu);
	// }
	//
	// @Override
	// public boolean onOptionsItemSelected(MenuItem item) {
	// // TODO Auto-generated method stub
	// final EditText text = new EditText(getActivity());
	// text.setInputType(InputType.TYPE_CLASS_TEXT
	// | InputType.TYPE_TEXT_VARIATION_URI);
	// AlertDialog dialog = new AlertDialog.Builder(getActivity())
	// .setView(text)
	// .setPositiveButton("确认", new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// // TODO Auto-generated method stub
	// Config.sharedConfig().setDevHost(
	// text.getText().toString());
	// Config.sharedConfig().save();
	// }
	// }).show();
	// return super.onOptionsItemSelected(item);
	// }

}
